<template>
  <a-drawer v-model:visible="vdata.visible" :maskClosable="false" width="40%" :title="'新建福分兑换奖品'">
    <a-form ref="formRef" layout="vertical" :model="vdata.saveObject" :rules="vdata.rules">
      <a-row type="flex" justify="space-between">
        <a-col span="11">
          <a-form-item label="机构" name="agentNo">
            <GzTreeSelect ref="gzThreeRef" v-model:value="vdata.saveObject['agentNo']" />
          </a-form-item>
        </a-col>
        <a-col span="11">
          <a-form-item label="选择小程序" name="appId">
            <a-select v-model:value="vdata.saveObject['appId']" placeholder="选择小程序">
              <a-select-option v-for="item in smallProgramlist" :key="item.appId" :value="item.appId">{{ item.name }}</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col span="11">
          <a-form-item label="所需福分" name="scoreNeed">
            <a-input v-model:value="vdata.saveObject['scoreNeed']" oninput="value=value.replace(/[^\d]/g,'')" placeholder="所需福分" style="width: 100%;" />
          </a-form-item>
        </a-col>
        <a-col span="11">
          <a-form-item label="奖品类型" name="awardType">
            <a-radio-group v-model:value="vdata.saveObject['awardType']" @change="changeFunc">
              <a-radio :value="0">卡券</a-radio> 
              <a-radio :value="1">实物</a-radio>
              <a-radio :value="2">虚拟券</a-radio>
            </a-radio-group>
          </a-form-item>
        </a-col>
        
        <a-col v-if="vdata.saveObject.awardType === 0" span="11">
          <a-form-item label="出资方" name="payAuthId">
            <a-select
              v-model:value="vdata.saveObject['payAuthId']"
              allowClear
              placeholder="请选择出资方"
              :field-names="{ label: 'ifName', value: 'payAuthId' }"
              :options="payAuthList"
              @change="handlePayAuthId"
            />
          </a-form-item>
        </a-col>
        <a-col span="11">
          <a-form-item label="活动类型" name="type">
            <a-radio-group v-model:value="vdata.saveObject['type']">
              <a-radio :value="0">福分商城</a-radio>
              <!-- <a-radio :value="1">权益商城</a-radio> -->
            </a-radio-group>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="限制黑名单" name="hasBlacklist">
            <a-radio-group v-model:value="vdata.saveObject['hasBlacklist']">
              <a-radio :value="0">不限制</a-radio>
              <a-radio :value="1">限制</a-radio>
            </a-radio-group>
          </a-form-item>
          <a-form-item v-if="vdata.saveObject.hasBlacklist == 1" label="" name="blacklistRuleIdList">
            <a-checkbox-group v-model:value="vdata.saveObject['blacklistRuleIdList']" :options="plainOptions" />
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
    <page-header-wrapper>
      <a-card class="table-card">
        <GzSearchForm :searchFunc="searchFunc" :resetFunc="()=>{ searchData={} }" searchConditionNum="6">
          <a-form-item>
            <a-input v-model:value="searchData['batchNo']" placeholder="批次号" />
          </a-form-item>
        </GzSearchForm>

        <!-- 列表渲染 -->

        <GzTable
          v-if="vdata.saveObject.awardType === 0"
          ref="infoTableRef"
          :table-columns="couponColumns"
          :init-data="true"
          :req-table-data-func="reqTableDataFunc"
          :search-data="searchData"
          :scrollX="600"
          rowKey="couponId"
          :row-selection="{ selectedRowKeys: vdata.selectedRowKeys, onSelect: onSelectChange, hideSelectAll: true }"
          :isPagination="false"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'couponPrice'">
              <span>{{ record.couponPrice ? record.couponPrice / 100 : '--' }}</span>
            </template>
            <template v-if="column.key === 'operation'">
              <GzTableColumns>
                <a-button type="link" @click="detailFunc(record.couponId)">详情</a-button>
              </GzTableColumns>
            </template>
          </template>
        </GzTable>

        <GzTable
          v-if="vdata.saveObject.awardType === 1"
          ref="infoTableRef"
          :table-columns="goodsColumns"
          :init-data="true"
          :req-table-data-func="reqTableDataFunc"
          :search-data="searchData"
          :scrollX="600"
          rowKey="goodsId"
          :row-selection="{ selectedRowKeys: vdata.selectedRowKeys, onSelect: onSelectChange, hideSelectAll: true }"
          :isPagination="false"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'goodsPrice'">
              <span>{{ record.goodsPrice ? record.goodsPrice / 100 : '--' }}</span>
            </template>
            <template v-if="column.key === 'operation'">
              <GzTableColumns>
                <a-button type="link" @click="detailFunc(record.goodsId)">详情</a-button>
              </GzTableColumns>
            </template>
          </template>
        </GzTable>
        <GzTable
          v-if="vdata.saveObject.awardType === 2"
          ref="infoTableRef"
          :table-columns="virtualColumns"
          :init-data="true"
          :req-table-data-func="reqTableDataFunc"
          :search-data="searchData"
          :scrollX="600"
          rowKey="virtualId"
          :row-selection="{ selectedRowKeys: vdata.selectedRowKeys, onSelect: onSelectChange, hideSelectAll: true }"
          :isPagination="false"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'operation'">
              <GzTableColumns>
                <a-button type="link" @click="detailFunc(record.virtualId)">详情</a-button>
              </GzTableColumns>
            </template>
          </template>
        </GzTable>
      </a-card>
    </page-header-wrapper>
    <div class="drawer-btn-center">
      <a-button :style="{ marginRight: '8px' }" style="margin-right:8px" @click="onClose">
        <close-outlined />
        取消
      </a-button>
      <a-button type="primary" :loading="vdata.btnLoading" @click="handleOkFunc">
        <check-outlined />
        保存
      </a-button>
    </div>
    <!-- <AwardDetail ref="awardDetailRef"/> -->
  </a-drawer>
  <component :is="vdata.component" ref="componentRef" />
</template>

<script setup lang="ts">
import GoodsDetail from '@/views/award/goods/Detail.vue'
import CouponDetail from '@/views/award/coupon/Detail.vue'
import VirtualCouponDetail from '@/views/award/virtualCoupon/Detail.vue'
import {$selectGoods,$getUndistributedList,$scoreAdd,$getEntList} from '../../../api/score/scoreMall/index'
import{$getAllGiveRule} from '@/api/activityManage/activityCreate/index'
import {$apiAgentLiteGetList} from '@/api/proxy/programManage/liteBanner/index'
import { ref, reactive, defineExpose, computed, watch, nextTick, getCurrentInstance } from 'vue'
const { $infoBox, $access } = getCurrentInstance()!.appContext.config.globalProperties
import { useAgentStore } from '@/store/modules/agent'
const agentInfoStore = useAgentStore().agentInfo
const plainOptions = ref([])
const formRef = ref()
const infoTableRef = ref()
const componentRef = ref()
const ruleListProduct = ref([]) as any
const props = defineProps(['callbackFunc'])

const searchData = ref({})

const vdata: any = reactive({
  visible: false,
  component: CouponDetail, // 动态组件
  selectedRowKeys: [],  // 选中要兑换的奖品
  saveObject: {},
  url: '/api/award/coupon/usable', // 奖品列表的请求地址
  rules: {
    awardType: [{ required: true, message: '奖品类型不能为空', trigger: 'blur' }],
    scoreNeed: [{ required: true, message: '所需福分不能为空', trigger: 'blur' }],
    agentNo: [{ required: true, message: '机构不能为空', trigger: 'blur' }],
    activityType : [{ required: true, message: '机构不能为空', trigger: 'blur' }],
    appId: [{ required: true, message: '小程序不能为空', trigger: 'change'},],
    hasBlacklist: [{ required: true, message: '请选择限不限制黑名单', trigger: ['blur'] }],
    blacklistRuleIdList: [{ required: true, message: '黑名单规则至少选择一个', trigger: ['blur'] }],

  }
})


function handlePayAuthId(){
  infoTableRef.value.refTable(true)
}

const URL = computed(()=>{
  const awardType = vdata.saveObject.awardType
  if(awardType === 0){
    // 未分配活动的卡券奖品列表
    return '/api/award/coupon/usable'
  }else if(awardType === 1){
    // 未分配活动的实物奖品列表
    return '/api/award/goods/usable'
  }else{
    // 未分配活动的虚拟券奖品列表
    return '/api/award/virtual/usable'
  }
})

const goodsColumns = reactive([
  { key: 'batchNo', title: '批次号',dataIndex: 'batchNo', width: 80, },
  { key: 'goodsName', title: '奖品名称',dataIndex: 'goodsName', width: 100, minWidth: 100, maxWidth: 120 },
  { key: 'goodsPrice', title: '奖品价值',dataIndex: 'goodsPrice', width: 80, minWidth: 80, maxWidth: 100 },
  { key: 'agentNo', title: '机构号',dataIndex: 'agentNo', width: 80, minWidth: 80, maxWidth: 100 },
  { key: 'operation', title: '操作', dataIndex: 'operation',width: 100, align: 'center' }
])
const couponColumns = reactive([
  { key: 'batchNo', title: '批次号',dataIndex: 'batchNo', width: 80, },
  { key: 'couponName', title: '奖品名称',dataIndex: 'couponName', width: 100, minWidth: 100, maxWidth: 120 },
  { key: 'couponPrice', title: '奖品价值',dataIndex: 'couponPrice', width: 80, minWidth: 80, maxWidth: 100 },
  { key: 'agentNo', title: '机构号',dataIndex: 'agentNo', width: 80, minWidth: 80, maxWidth: 100 },
  { key: 'operation', title: '操作', dataIndex: 'operation',width: 100, align: 'center' }
])
const virtualColumns = reactive([
  { key: 'batchNo', title: '批次号',dataIndex: 'batchNo', width: 80, },
  { key: 'goodsName', title: '奖品名称',dataIndex: 'goodsName', width: 100, minWidth: 100, maxWidth: 120},
  { key: 'agentNo', title: '机构号',dataIndex: 'agentNo', width: 80, minWidth: 80, maxWidth: 100 },
  { key: 'operation', title: '操作', dataIndex: 'operation',width: 100, align: 'center' }
])

function searchFunc() {
  infoTableRef.value.refTable(true)
}
// 请求table接口数据
function reqTableDataFunc(params: any) {
  
  if(vdata.saveObject.awardType === 0){ // 卡券 需要过滤满减随机减卡券 只查询微信代金券 couponType = 5
    params.couponType = 5
  }
  params.payAuthId = vdata.saveObject.payAuthId
  params.agentNo = vdata.saveObject.agentNo
  return new Promise(resolve => {
    $getUndistributedList(URL.value,{ ...params, state: 2 }).then(res => {
      resolve({ records: res })
    })
  })
}

function changeFunc(e){
  const awardType = vdata.saveObject.awardType
  vdata.component = awardType === 0 ? CouponDetail : (awardType === 1 ? GoodsDetail : VirtualCouponDetail)
  vdata.selectedRowKeys = []
}


// 奖品详情
function detailFunc(recordId){
  componentRef.value.show(recordId)
}

// 选择兑换的商品
function onSelectChange(record){
  const awardType = vdata.saveObject.awardType
  const id = awardType === 0 ? 'couponId' : (awardType === 1 ? 'goodsId' : 'virtualId')
  vdata.selectedRowKeys = [record[id]]
  
}

function handleOkFunc() {
  formRef.value.validate().then(()=>{
    if(vdata.selectedRowKeys.length === 0){
      $infoBox.message.warn('请选择要兑换的商品')
      return
    }
    vdata.btnLoading = true
    $scoreAdd({ ...vdata.saveObject, awardId: vdata.selectedRowKeys[0] }).then(() => {
      $infoBox.message.success('新增成功')
      props.callbackFunc()
      onClose()
    }).finally(()=>{
      vdata.btnLoading = false
    })
  }).catch(()=>{})
}

function show() {
  // 获取出资方列表
  getPayAuthList()
  vdata.saveObject = {
    awardType: 0,
    type: 0,
    periodType:0,
    hasBlacklist: 0,
    agentNo: agentInfoStore.agentNo,
  }
  vdata.selectedRowKeys = []
  plainOptions.value = []
  vdata.visible = true
    getBlacklistRuleList()
    nextTick(() => {
       infoTableRef.value.refTable(true) 
      }
  )
}
/**
 * 获取出资方列表
 */
const payAuthList = ref([])
function getPayAuthList() {
  $getEntList({ pageSize: 100 }).then((result) => {
    payAuthList.value = result.records
  })
}

function onClose() {
  vdata.visible = false
}

defineExpose({
  show
})

// 获取黑名单列表
function getBlacklistRuleList(){
  $getAllGiveRule(null).then(res => {
    plainOptions.value = res.map(item => {
      return {
        label: item.ruleName,
        value: item.blacklistRuleId
      }
    })
  })
 
}
const smallProgramlist = ref([
  { appId: '', name: '' } as any

]) 
// 获取小程序列表
function  getLiteBannerList() {
  $apiAgentLiteGetList({ type: 1,agentNo:vdata.saveObject.agentNo }).then(res => {
    smallProgramlist.value = res
    if (smallProgramlist.value.length > 0) {
      vdata.saveObject.appId = smallProgramlist.value[0].appId // 默认选择第一个小程序
    } else {
      vdata.saveObject.appId = null // 如果没有小程序，清空选择
    }
  })
}
watch(() => vdata.saveObject.agentNo, (newVal) => {
  nextTick(() => {
    infoTableRef.value.refTable(true)
    getLiteBannerList() // 监听机构号变化，重新获取小程序列表
  })
}, { immediate: true })

</script>